package com.sgu6.sgu6_machine.ui.fragment.set;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.sgu6.middleware.manager.ThreadManager;
import com.sgu6.middleware.enums.MachineCmdEnum;
import com.sgu6.middleware.util.HexUtil;
import com.sgu6.serialport.manager.SerialPortManager;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.adapter.MotorAdapter;
import com.sgu6.sgu6_machine.base.BaseF;
import com.sgu6.sgu6_machine.config.MachineConfig;
import com.sgu6.sgu6_machine.config.MotorConfig;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.listener.OnMotorButtonClickListener;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 电机设置
 */
public class ViolenceF extends BaseF implements OnMotorButtonClickListener {

    @BindView(R.id.lv_motor)
    ListView lvMotor;
    @BindView(R.id.label_mill)
    TextView labelMill;
    @BindView(R.id.tv_launcher_time)
    TextView tvLauncherTime;
    @BindView(R.id.tv_mill_times)
    TextView tvMillTimes;
    @BindView(R.id.tv_mill_duration)
    TextView tvMillDuration;
    @BindView(R.id.tv_mill_count)
    TextView tvMillCount;
    @BindView(R.id.btn_start)
    Button btnStart;
    @BindView(R.id.btn_stop)
    Button btnStop;

    Unbinder unbinder;

    private MotorAdapter adapter;
    private List<MotorConfig> motorConfigs = new ArrayList<>();
    private List<String> startCommands = new ArrayList<>();
    private List<String> stopCommands = new ArrayList<>();
    private EditText etTimes, etGap, etLauncherTime;
    private TextView tvCount;
    private String strTimes, strGap, strLauncherTime;
    private int times, gap, launcherTime;
//    private int count = 0, total = 0;
    private int[] count = new int[]{0,0,0,0,0};
    private int[] total = new int[]{5000,5000,5000,5000,5000};
    private boolean isTest = false;


    public static ViolenceF newInstance() {
        return new ViolenceF();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_violence, container, false);
        unbinder = ButterKnife.bind(this, v);
        init();
        adapter = new MotorAdapter(requireContext(), motorConfigs, this);
        lvMotor.setAdapter(adapter);

        return v;
    }

    private void init() {
        motorConfigs.add(new MotorConfig("碾米电机：", 1, 5000, 0, 5));
        motorConfigs.add(new MotorConfig("下米电机：", 1, 5000, 0, 5));
        if (!MachineContainer.machineConfigDto.withPack){
            motorConfigs.add(new MotorConfig("拉膜电机：", 1, 5000, 0, 2));
            motorConfigs.add(new MotorConfig("封膜电机：", 1, 5000, 0, 5));
        }
        motorConfigs.add(new MotorConfig("开关门电机：", 1, 5000, 0, 20));

        startCommands.add(MachineCmdEnum.启动碾米电机.code());
        startCommands.add(MachineCmdEnum.启动拉膜电机.code());
        startCommands.add(MachineCmdEnum.启动下米电机.code());
        startCommands.add(MachineCmdEnum.启动封膜电机.code());
        startCommands.add(MachineCmdEnum.开门电机开到位.code());

        stopCommands.add(MachineCmdEnum.立即关闭碾米电机.code());
        stopCommands.add(MachineCmdEnum.立即关闭拉膜电机.code());
        stopCommands.add(MachineCmdEnum.立即关闭下米电机.code());
        stopCommands.add(MachineCmdEnum.立即关闭封膜电机.code());
        stopCommands.add(MachineCmdEnum.开门电机关到位.code());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onStartClick(View v) {
        Log.i(TAG, "onStartClick: " + v.getTag());
        isTest = true;
        final int position = (int) v.getTag();
        View parent = (View) v.getParent();
        getStartValue(parent);
        total[position] = times;

        ThreadManager.getThreadPollProxy().execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (count[position] < total[position] && isTest)
                        try {
                            SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(startCommands.get(position)));
                            Thread.sleep(launcherTime * 1000);
                            SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(stopCommands.get(position)));
                            if (position == 4) {
                                Thread.sleep(1000);
                                SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.立即停止开门电机.code()));
                            }
                            count[position]++;
                            Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tvCount.setText(String.valueOf(count[position]));
                                }
                            });
                            Thread.sleep(gap * 1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    else {
                        isTest = false;
                        break;
                    }
                }
            }
        });
    }

    @Override
    public void onStopClick(View v) {
        isTest = false;
        int position = (int) v.getTag();
//        SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(stopCommands.get(position)));
        Log.i(TAG, "onStopClick: " + v.getTag());
    }

    @Override
    public void onResetClick(View v) {
        isTest = false;
        int position = (int) v.getTag();
        tvCount = ((View) v.getParent()).findViewById(R.id.tv_count);
        count[position] = 0;
        tvCount.setText(String.valueOf(count[position]));
        Log.i(TAG, "onResetClick: " + v.getTag());
    }

    private void getStartValue(View parent) {

        etTimes = parent.findViewById(R.id.et_times);
        strTimes = etTimes.getText().toString().trim();

        etGap = parent.findViewById(R.id.et_gap);
        strGap = etGap.getText().toString().trim();

        etLauncherTime = parent.findViewById(R.id.et_launcher_time);
        strLauncherTime = etLauncherTime.getText().toString().trim();

        tvCount = parent.findViewById(R.id.tv_count);

        times = Integer.parseInt(strTimes);
        gap = Integer.parseInt(strGap);
        launcherTime = Integer.parseInt(strLauncherTime);

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.i(TAG, "onHiddenChanged: " + hidden);
//        if (hidden) {
////            SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.自动模式.code()));
////        } else {
////            SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.手动模式.code()));
////        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        SerialPortManager.getInstance().sendBytes(HexUtil.HexString2Bytes(MachineCmdEnum.自动模式.code()));
    }


}
